package com.capa.ui.chat

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.net.http.SslError
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.text.Editable
import android.text.Selection
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.webkit.SslErrorHandler
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.webkit.WebViewFeature
import com.alibaba.fastjson.JSONException
import com.capa.BR
import com.capa.R
import com.capa.basic.BaseFragment
import com.capa.databinding.FragmentChatBinding
import com.capa.ui.chat.adapter.ChatAdapter
import com.capa.ui.chat.adapter.MyRecognizerDialog
import com.capa.utils.SPreference
import com.iflytek.cloud.ErrorCode
import com.iflytek.cloud.InitListener
import com.iflytek.cloud.RecognizerResult
import com.iflytek.cloud.SpeechConstant
import com.iflytek.cloud.SpeechError
import com.iflytek.cloud.SpeechRecognizer
import com.iflytek.cloud.ui.RecognizerDialog
import com.iflytek.cloud.ui.RecognizerDialogListener
import com.tencent.mm.opensdk.utils.Log
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import org.json.JSONObject
import kotlin.concurrent.thread


class ChatFragment : BaseFragment<FragmentChatBinding, ChatViewModel>() {
    
    private lateinit var adapter: ChatAdapter

    //用与语音识别的对象
    private lateinit var mIat: SpeechRecognizer;
    //语音听写UI
    private lateinit var mIatDialog: MyRecognizerDialog;
    //存储语音识别结果
    private var mIatResults:HashMap<String,String> = LinkedHashMap()
    private var mEngineType:String = SpeechConstant.TYPE_CLOUD;// 引擎类型
    private val language = "en_us" //识别语言

    private val resultType = "json" //结果内容数据格式

    companion object{
        const val  TAG = "ChatFragment";
    }


    override fun initVariableId(): Int = BR.viewModel

    override fun initContentView(
        inflater: LayoutInflater?,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): Int = R.layout.fragment_chat

    override fun initParam() {

    }

    override fun onDestroy() {
        super.onDestroy()
        // 退出时释放连接
        mIat.cancel();
        mIat.destroy();
    }

    override fun initViewObservable() {

    }


    /**
     * 初始化监听器。
     */
    private val mInitListener = InitListener { code: Int ->

        Log.d(TAG, "SpeechRecognizer init() code = $code")
        if (code != ErrorCode.SUCCESS) {
            showMsg("初始化失败，错误码：$code,请点击网址https://www.xfyun.cn/document/error-code查询解决方案")
        }
    }

    /**
     * 听写UI监听器
     */
    private val mRecognizerDialogListener: RecognizerDialogListener =
        object : RecognizerDialogListener {
            override fun onResult(results: RecognizerResult, isLast: Boolean) {
               printResult(results);
            }

            /**
             * 识别回调错误.
             */
            override fun onError(error: SpeechError) {
                showMsg(error.getPlainDescription(true))
            }
        }

    /**
     * 提示消息
     * @param msg
     */
    private fun showMsg(msg: String) {
        Toast.makeText(requireContext() , msg, Toast.LENGTH_SHORT).show()
    }


    /**
     * 数据解析
     *
     * @param results
     */
    fun printResult(results: RecognizerResult) {
        val text: String = com.capa.utils.JsonParser.parseIatResult(results.resultString)

        var sn: String? = null
        // 读取json结果中的sn字段
        try {
            val resultJson: JSONObject = JSONObject(results.resultString)
            sn = resultJson.optString("sn")
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        mIatResults.put(sn!!, text);
        var resultBuffer = StringBuffer()
        for(key in mIatResults.keys){
            resultBuffer.append(mIatResults[key])
        }
        viewModel?.setInputMessage(resultBuffer.toString())
        viewModel?.sendMessageToDeepSeek()
    }


    fun setParam() {
        // 清空参数
        mIat.setParameter(SpeechConstant.PARAMS, null)
        // 设置听写引擎
        mIat.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType)
        // 设置返回结果格式
        mIat.setParameter(SpeechConstant.RESULT_TYPE, resultType)

        if (language == "zh_cn") {
            val lag : String by SPreference(
                "iat_language_preference",
                "mandarin"
            )
            android.util.Log.e(TAG, "language:$language") // 设置语言
            mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn")
            // 设置语言区域
            mIat.setParameter(SpeechConstant.ACCENT, lag)
        } else {
            mIat.setParameter(SpeechConstant.LANGUAGE, language)
        }
        android.util.Log.e(TAG, "last language:" + mIat.getParameter(SpeechConstant.LANGUAGE))

        //此处用于设置dialog中不显示错误码信息
        //mIat.setParameter("view_tips_plain","false");

        // 设置语音前端点:静音超时时间，即用户多长时间不说话则当做超时处理
        mIat.setParameter(
            SpeechConstant.VAD_BOS,
            SPreference.preference.getString("iat_vadbos_preference", "4000")
        )

        // 设置语音后端点:后端点静音检测时间，即用户停止说话多长时间内即认为不再输入， 自动停止录音
        mIat.setParameter(
            SpeechConstant.VAD_EOS,
            SPreference.preference.getString("iat_vadeos_preference", "1000")
        )

        // 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
        mIat.setParameter(
            SpeechConstant.ASR_PTT,
            SPreference.preference.getString("iat_punc_preference", "0")
        )

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        mIat.setParameter(SpeechConstant.AUDIO_FORMAT, "wav")
        mIat.setParameter(
            SpeechConstant.ASR_AUDIO_PATH,
            Environment.getExternalStorageDirectory().toString() + "/msc/iat.wav"
        )
    }
}